<?php
namespace control;
/*
*宿舍费用记录类
*/

class dormitoryFeeRecordClass extends adIndexClass
{
    private const page = 'dormitoryFeeRecord';
    private const table = 'dormitory_fee_record';
    private const title = '宿舍费用记录';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'month' => [
                        'name'  => "月份",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'building'  => [
                        'name'  => "楼号",
                        'width' => 100,
                    ],
                    'floor'         => [
                        'name'  => '楼层',
                        'width' => 100,
                    ],
                    'room'          => [
                        'name'  => '宿舍号',
                        'width' => 100
                    ],
                    'electricityFee'          => [
                        'name'  => "电费(".static::$unit.")",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'waterFee'          => [
                        'name'  => "水费(".static::$unit.")",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'gasFee'          => [
                        'name'  => "燃气费(".static::$unit.")",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'propertyFee'          => [
                        'name'  => "物业费(".static::$unit.")",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'otherFee'          => [
                        'name'  => '其他费用('.static::$unit.')',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'total'          => [
                        'name'  => '合计('.static::$unit.')',
                        'width' => 100,
                    ],
                    'stid'          => [
                        'name'  => "制单人",
                        'width' => 100,
                    ],
                    'time'          => [
                        'name'  => "制单日期",
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "楼号"     => repeatSelect(array('change'=>'getFloor','sqlForm'=>"dormitory where state ='启用'",'sqlField'=>'building','name'=>'building')),
                    '楼层' => repeatSelect(array('change'=>'getRoom','sqlForm'=>"dormitory where state ='启用' and building = ''",'sqlField'=>'floor','name'=>'floor')),
                ],
                [
                    '宿舍号'   => idSelect(array('change'=>'getPeople','sqlForm'=>"dormitory where state ='启用' and building = '' and floor = ''",'sqlField'=>'room','sqlId'=>'id','name'=>'dormitoryId')),
                    "月份" => text(array("name" => "creatTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button)).$this->editJs();
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
        );
        //全等查询数组
        $equal = array(
            "dormitoryId" => $this->post('dormitoryId'),
        );
        $and = "";
        $mAnd = '';
        if (empty($this->post('dormitoryId'))){
            if ($this->post('building')){
                $mAnd.=" and building = '".$this->post('building')."'";
            }
            if ($this->post('floor')){
                $mAnd.=" and floor = '".$this->post('floor')."'";
            }
            $and.=$mAnd?" and dormitoryId in (select id from dormitory where 1=1 {$mAnd})":'';
        }
        if ($this->post('creatTime')) {
            $arr = explode('~', $this->post('creatTime'));
            $arr[0] = trim($arr[0]);
            $arr[1]   = trim(end($arr));
            $and .=" and month >= '$arr[0]' and month <='$arr[1]'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'month desc,time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            $dormitory = query('dormitory',"id = '$array[dormitoryId]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "building":
                    case "floor":
                    case "room":
                        $row[] = $dormitory[$key];
                        break;
                    case "total":
                        $total = $array['electricityFee']+$array['waterFee']+$array['gasFee']+$array['propertyFee']+$array['otherFee'];
                        $row[] = $total;
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        $dormitory = query('dormitory',"id = '$info[dormitoryId]'");
        $dormitory['maxPeople'] = $dormitory['maxPeople']?:0;
        $livePeople = static::total(array('table'=>'dormitory_record','where'=>"dormitoryId = '".$dormitory['id']."' and state = '入住'"));
        $people = $dormitory['maxPeople']."/".$livePeople;
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "月份：" => text(["name" => "month",'laydate'=>['type'=>'month'], 'class' => 'text', "value" => $info['month']]),
                ],
                [
                    must . "宿舍号：" => repeatSelect(array('title'=>'楼号','value'=>$dormitory['building'],'change'=>'getFloor','sqlForm'=>"dormitory where state ='启用'",'sqlField'=>'building','name'=>'building')).
                        repeatSelect(array('title'=>'楼层','value'=>$dormitory['floor'],'change'=>'getRoom','sqlForm'=>"dormitory where state ='启用' and building = '$dormitory[building]'",'sqlField'=>'floor','name'=>'floor')).
                        idSelect(array('title'=>'宿舍号','change'=>'getPeople','value'=>$dormitory['id'],'sqlForm'=>"dormitory where state ='启用' and building = '$dormitory[building]' and floor = '$dormitory[floor]'",'sqlField'=>'room','sqlId'=>'id','name'=>'dormitoryId')),
                ],
                [
                    "可住/已住"=>"<span id='livePeople'>{$people}</span>"
                ],
                [
                    must . "电费：" =>text(array("name" => "electricityFee",'value'=>$info['electricityFee'], "unit" =>  static::$unit ,  'class' => 'text')),
                    "水费：" =>text(array("name" => "waterFee",'value'=>$info['waterFee'], "unit" =>  static::$unit ,  'class' => 'text')),
                ],
                [
                    "燃气费：" =>text(array("name" => "gasFee",'value'=>$info['gasFee'], "unit" =>  static::$unit ,  'class' => 'text')),
                    "物业费：" =>text(array("name" => "propertyFee",'value'=>$info['propertyFee'], "unit" =>static::$unit,  'class' => 'text')),
                ],
                [
                    "其他费用：" =>text(array("name" => "otherFee",'value'=>$info['otherFee'], "unit" =>  static::$unit ,  'class' => 'text')),
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']])
                ],
            ],
        ]);
        $html.=$this->editJs();
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 400, "html" => $html));
    }
    /**
     *
     * @return string
     */
    public function editJs(): string
    {
        return <<<eof
<script>
function getFloor(e){
    let form = $(e).closest('form')
    $.post(root+'control/adIndex.html?cla=dormitoryRecord&fun=getFloor',{building:e.value},function(res) {
        form.find("[name='floor']").empty().append(res.floorHtml);
        form.find("[name='dormitoryId']").empty().append(res.roomHtml);
        $("#livePeople").html('-/-');
    },'json')
}
function getRoom(e){
    let form = $(e).closest('form')
    let building= form.find("[name='building']").val();
    $.post(root+'control/adIndex.html?cla=dormitoryRecord&fun=getRoom',{floor:e.value,building:building},function(res) {
        form.find("[name='dormitoryId']").empty().append(res.roomHtml);
    },'json')
}
function getPeople(e){
     $.post(root+'control/adIndex.html?cla=dormitoryRecord&fun=getPeople',{dormitoryId:e.value},function(res) {
        $("#livePeople").html(res.html);
    },'json')
}
</script>
eof;

    }
    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'dormitoryId' => $this->post('dormitoryId'),
            'month' => $this->post('month'),
            'electricityFee' => $this->post('electricityFee'),
            'waterFee' => $this->post('waterFee'),
            'gasFee' => $this->post('gasFee'),
            'propertyFee' => $this->post('propertyFee'),
            'otherFee' => $this->post('otherFee'),
            'text' => $this->post('text'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'dormitoryId' => '宿舍号',
            'month' => '月份',
            'electricityFee' => '电费',
        ];
        $rules = [
            'dormitoryId' => 'required',
            'month' => 'required',
            'electricityFee' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'SSFY'.date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            $_SESSION[self::page]['id'] = $info['id'];
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
            );

            $button = [];
            if ($this->power(self::page, "edit")) {
                $button[] = [
                    "name" => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, "del")){
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            $dormitory = query('dormitory',"id = '$info[dormitoryId]'");
            $dormitory['maxPeople'] = $dormitory['maxPeople']?:0;
            $livePeople = static::total(array('table'=>'dormitory_record','where'=>"dormitoryId = '".$dormitory['id']."' and state = '入住'"));
            $people = $dormitory['maxPeople']."/".$livePeople;
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '详细信息' => array(
                    array(
                        "宿舍号" => $dormitory['building'].'-'.$dormitory['floor'].'-'.$dormitory['room'],
                        "可住/已住" => $people,
                        "电费(".static::$unit.")" => $info['electricityFee'],
                        "水费(".static::$unit.")" => $info['waterFee'],
                    ),
                    array(
                        "燃气费(".static::$unit.")" => $info['gasFee'],
                        "物业费(".static::$unit.")" => $info['propertyFee'],
                        "其他费用(".static::$unit.")" => $info['otherFee'],
                        "合计(".static::$unit.")" => $info['electricityFee']+$info['waterFee']+$info['gasFee']+$info['propertyFee']+$info['otherFee'],
                    ),
                    array(
                        "备注" => pre($info['text']),
                    ),
                ),
                '系统信息' => array(
                    array(
                        "单据编号" => $info['orderNo'],
                        "制单人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                        "更新时间" => $info['updateTime'],
                    ),
                )
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }
    /**
     * 启用/停用
     */
    public function stateSwitch()
    {
        $type = $this->post('type');
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否确认退宿？",
            ),
        ), 'hidden' => hidden(array('name' => 'type', 'value' => $type))));
        //返回
        return $this->layer(array("title" => "退宿", "height" => 165, "html" => $html));
    }

    /**
     * 启用/停用
     */
    public function stateSwitchEdit()
    {
        $id = $this->post('id');
        $type = $this->post('type');
        $info = query(self::table," id = '$id'");
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($info['id'])) {
            $json['warn'] = "未找到此宿舍档案";
        } elseif (!in_array($type, ['退宿'])) {
            $json['warn'] = "类型错误";
        } else {
            $field = [
                'state' => $type,
                'outDate'=>$this->date
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id ='$id'"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "的状态为【{$type}】， id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power =$word= '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word'=>$word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}
